﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXYW.Entities;
using WXYW.DAL;

namespace WXYW.BLL
{
    public class ProblemTypeService : RepositoryBase
    {
        public List<ProblemType> GetAllProblemType()
        {
            return GetEntities<ProblemType>().ToList();
        }

        public ProblemType GetTypeByID(int ID)
        {
            return GetEntities<ProblemType>(p => p.ID == ID).FirstOrDefault();
        }

        public bool IsDuplicateByUpdateName(string newName, int updateID)
        {
            return GetEntities<ProblemType>(p => p.Name == newName && p.ID != updateID).Count() > 0;
        }

        public void UpdateName(string newName, int updateID)
        {
            ProblemType problemType = GetTypeByID(updateID);
            problemType.Name = newName;
            UpdateEntity(problemType);
        }

        public void AddProblemType(ProblemType problemType)
        {
            InsertEntity(problemType);
        }

        public void DeleteProblemTypeByID(int problemTypeID)
        {
            // 先检查是否有外键关系的表格使用该故障类型
            ProviderService providerService = new ProviderService();
            List<Document> documents = providerService.GetDocumentByProblemTypeID(problemTypeID);
            if (null != documents && documents.Count() > 0)
            {
                throw new Exception("该故障类型已经被使用");
            }

            ApplicationProductService appProductService = new ApplicationProductService();
            List<ApplicationProduct> appProducts = appProductService.GetAppProductByProblemTypeID(problemTypeID);
            if (null != appProducts && appProducts.Count() > 0)
            {
                throw new Exception("该故障类型已经被使用");
            }

            List<ApplicationProductHistory> appProductHistorys = appProductService.GetAppProductHistoryByProblemTypeID(problemTypeID);
            if (null != appProductHistorys && appProductHistorys.Count() > 0)
            {
                throw new Exception("该故障类型已经被使用");
            }

            DeleteEntities<ProblemType>(s => s.ID == problemTypeID, Guid.Empty);
        }
    }
}
